﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace ColorLib
{
	public class ColorHistogram : GenericColorCube<int>
	{
		/*
		public class ColorCounter
		{
			public ColorCounter() { }
			public ColorCounter(int i) { n = i; }
			public int n = 0;
		}
		*/
		public ColorHistogram() : base() { }
		public ColorHistogram(int n) : base(n) { }
		public ColorHistogram(Dictionary<Color, int> d)
			: base()
		{
			foreach (KeyValuePair<Color, int> x in d)
			{
				Add(x.Key, x.Value);
			}
		}
		public void SwapCube(ColorHistogram other)
		{
			System.Diagnostics.Debug.Assert(cubeSize == other.cubeSize);
			List<List<List<ColorNode>>> data = cube;
			int n = count;
			cube = other.cube;
			count = other.count;
			other.cube = data;
			other.count = n;

		}

		public void AddCount(Color color, int n)
		{
			int r = (color.R / (256 / cubeSize));
			int g = (color.G / (256 / cubeSize));
			int b = (color.B / (256 / cubeSize));
			ColorNode cn = cube[r][g][b];
			int val = 0;
			if (cn.Colors.TryGetValue(color, out val))
			{
				if (val + n != 0)
					cn.Colors[color] = val + n;
				else
				{
					cn.Remove(color);
					count--;
				}
			}
			else
			{
				cn.Colors.Add(color, n);
				count++;
			}
		}
		public void AddCount(Color color)
		{
			AddCount(color, 1);
		}
		public int GetAllCounts(Dictionary<Color, int> d)
		{
			for (int i = 0; i < cubeSize; i++)
			{
				for (int j = 0; j < cubeSize; j++)
				{
					for (int k = 0; k < cubeSize; k++)
					{
						ColorNode cn = cube[i][j][k];
						foreach (KeyValuePair<Color, int> p in cn.Colors)
							d.Add(p.Key, p.Value);
					}

				}
			}
			return d.Count;
		}
		public void RemapColors(Dictionary<Color, Color> colormap)
		{
			foreach (KeyValuePair<Color, Color> cc in colormap)
			{
				int n = 0;
				if (TryGetValue(cc.Key, ref n))
				{
					AddCount(cc.Value, n);
					Remove(cc.Key);
				}
			}
		}
		public void RemapColors(IList<Color> from, Color to)
		{
			int sum = 0;
			foreach (Color c in from)
			{
				int n = 0;
				if (TryGetValue(c, ref n))
				{
					sum += n;
					Remove(c);
				}
			}
			AddCount(to, sum);
		}

		public ColorHistogram CloneHistogram()
		{
			ColorHistogram h = new ColorHistogram();
			h.Replicate(this);
			return h;
		}
	}
}
